<template>
  <div class="paginated-list">
    <div class="content">
<!--      <h2>用户:{{userInfo.username}}</h2>-->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="小红书号：">
          <el-input v-model="searchForm.redBookUser" placeholder="小红书号"></el-input>
        </el-form-item>
        <el-form-item label="新增日期：">
          <el-config-provider :locale="locale">
            <el-date-picker
                v-model="searchForm.createTimeRange"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                start-placeholder="开始使用时间"
                end-placeholder="结束使用时间"
            />
          </el-config-provider>
<!--          <el-date-picker v-model="addForm.createTime" type="date" placeholder="选择日期"></el-date-picker>-->
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="searchForm.remark" placeholder="备注"></el-input>
        </el-form-item>
        <el-form-item label="同行账号标注:">
          <el-select style="width: 180px" v-model="searchForm.same" placeholder="请选择">
            <el-option label="蓬莱小课软广号" value="蓬莱小课软广号"></el-option>
            <el-option label="蓬莱小课暗广号" value="蓬莱小课暗广号"></el-option>
            <el-option label="德云测" value="德云测"></el-option>
            <el-option label="番茄酱暗广号" value="番茄酱暗广号"></el-option>
            <el-option label="凡猫" value="凡猫"></el-option>
            <el-option label="培训同行" value="培训同行"></el-option>
            <el-option label="已报名学员" value="已报名学员"></el-option>
            <el-option label="已加微信客户" value="已加微信客户"></el-option>
            <el-option label="未加微信客户" value="未加微信客户"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleAdd" :disabled="isAdding">新增</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" style="width: 100%" :header-cell-style="headerCellStyle">
        <el-table-column prop="xiaohongshuId" label="小红书号" width="180">
          <template #default="scope">
            <span class="highlight">{{ scope.row.redBookUser }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="same" label="同行账号标注" width="180"></el-table-column>
        <el-table-column prop="createTime" label="新增日期" width="180"></el-table-column>
        <el-table-column prop="searchNum" label="搜索次数" width="180"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="pagination">
      </el-pagination>

      <!-- 修改对话框 -->
      <el-dialog title="修改信息" v-model="editDialogVisible" width="30%">
        <el-form :model="editForm" label-width="120px">
          <el-form-item label="小红书号">
            <el-input v-model="editForm.redBookUser" disabled></el-input>
          </el-form-item>
          <el-form-item label="同行账号标注">
            <el-select v-model="editForm.same" placeholder="请选择">
              <el-option label="蓬莱小课软广号" value="蓬莱小课软广号"></el-option>
              <el-option label="蓬莱小课暗广号" value="蓬莱小课暗广号"></el-option>
              <el-option label="德云测" value="德云测"></el-option>
              <el-option label="番茄酱暗广号" value="番茄酱暗广号"></el-option>
              <el-option label="凡猫" value="凡猫"></el-option>
              <el-option label="培训同行" value="培训同行"></el-option>
              <el-option label="已报名学员" value="已报名学员"></el-option>
              <el-option label="已加微信客户" value="已加微信客户"></el-option>
              <el-option label="未加微信客户" value="未加微信客户"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="editForm.remark" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmEdit">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 新增对话框 -->
      <el-dialog title="新增信息" v-model="addDialogVisible" width="30%">
        <el-form :model="addForm" label-width="120px">
          <el-form-item label="小红书号">
            <el-input v-model="addForm.redBookUser" placeholder="请输入小红书号"></el-input>
          </el-form-item>
          <el-form-item label="同行账号标注">
            <el-select v-model="addForm.same" placeholder="请选择">
              <el-option label="蓬莱小课软广号" value="蓬莱小课软广号"></el-option>
              <el-option label="蓬莱小课暗广号" value="蓬莱小课暗广号"></el-option>
              <el-option label="德云测" value="德云测"></el-option>
              <el-option label="番茄酱暗广号" value="番茄酱暗广号"></el-option>
              <el-option label="凡猫" value="凡猫"></el-option>
              <el-option label="培训同行" value="培训同行"></el-option>
              <el-option label="已报名学员" value="已报名学员"></el-option>
              <el-option label="已加微信客户" value="已加微信客户"></el-option>
              <el-option label="未加微信客户" value="未加微信客户"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="addForm.remark" type="textarea" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
       <span class="dialog-footer">
         <el-button @click="addDialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="confirmAdd" :disabled="isAdding">确 定</el-button>
       </span>
        </template>
      </el-dialog>

    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/request/request';
import zhCn from "element-plus/es/locale/lang/zh-cn";
const locale = zhCn;
const searchForm = ref({
  redBookUser: '',
  createTimeRange: [],// 用于存储开始和结束时间
  remark: '',
  same: ''
});

const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const isAdding = ref(false); // 添加加载状态

// 初始化表单数据
function resetForm() {
  searchForm.value = {
    redBookUser: '',
    createTimeRange: [],//用于存储开始和结束时间
    remark: ''
  };
}

async function fetchData() {
  try {
    const response = await request.post('customer/getCustomerList', {
      //接受查询时间
      redBookUser: searchForm.value.redBookUser,
      startTime: searchForm.value.createTimeRange[0],
      endTime: searchForm.value.createTimeRange[1],
      remark: searchForm.value.remark,
      same: searchForm.value.same,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });
    console.log('获取数据成功:', response);
    tableData.value = response.data.list;
    total.value = response.data.total;
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败，请稍后再试');
  }
}

function handleSearch() {
  currentPage.value = 1;
  fetchData();
  resetForm(); // 重置表单数据
}

function handleSizeChange(newSize) {
  pageSize.value = newSize;
  fetchData();
}

function handleCurrentChange(newPage) {
  currentPage.value = newPage;
  fetchData();
}

function headerCellStyle() {
  return {
    backgroundColor: '#f0f9eb',
    color: '#67c23a',
    fontWeight: 'bold'
  };
}

// 删除操作
function handleDelete(index, row) {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteCustomer(row.id);
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

async function deleteCustomer(id) {
  try {
    const response = await request.delete('/customer/deleteCustomer/'+id);
    console.log('删除成功:', response);
    ElMessage.success('删除成功');
    fetchData(); // 重新获取数据
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败，请稍后再试');
  }
}

// 修改操作
const editDialogVisible = ref(false);
const editForm = ref({
  id: '',
  redBookUser: '',
  same: '',
  remark: ''
});

function handleEdit(index, row) {
  editForm.value = { ...row };
  editDialogVisible.value = true;
}
async function confirmEdit() {
  try {
    const response = await request.put('/customer/updateCustomer', {
      id: editForm.value.id,
      redBookUser: editForm.value.redBookUser,
      same: editForm.value.same,
      remark: editForm.value.remark
    });
    console.log('修改成功:', response);
    ElMessage.success('修改成功');
    editDialogVisible.value = false;
    fetchData(); // 重新获取数据
  } catch (error) {
    console.error('修改失败:', error);
    ElMessage.error('修改失败，请稍后再试');
  }
}

// 新增操作
const addDialogVisible = ref(false);
const addForm = ref({
  redBookUser: '',
  same: '',
  remark: ''
});

function handleAdd() {
  addForm.value = {
    redBookUser: '',
    same: '',
    remark: ''
  };
  addDialogVisible.value = true;
}

async function confirmAdd() {
  if (!addForm.value.redBookUser || !addForm.value.same) {
    ElMessage.error('小红书号和同行账号标注不能为空');
    return;
  }

  isAdding.value = true; // 设置加载状态

  try {
    const response = await request.post('/customer/addCustomer', {
      redBookUser: addForm.value.redBookUser,
      same: addForm.value.same,
      remark: addForm.value.remark
    });
    console.log('新增成功:', response);
    ElMessage.success('新增成功');
    addDialogVisible.value = false;
    fetchData(); // 重新获取数据
  } catch (error) {
    console.error('新增失败:', error);
  } finally {
    isAdding.value = false; // 重置加载状态
  }
}

// 确保在组件卸载时断开 ResizeObserver 的连接
const resizeObserver = new ResizeObserver(entries => {
  // 处理 resize 事件
  for (let entry of entries) {
    // 示例：处理 entry
    console.log('ResizeObserver entry:', entry);
  }
});

const userInfo = ref({
  username: ''
});
// 获取用户信息
function fetchUserInfo() {
  const storedUsername = localStorage.getItem('username');
  if (storedUsername) {
    userInfo.value = storedUsername;
    console.log('获取到的用户名:', storedUsername);
  } else {
    console.error('localStorage 中没有找到 username');
  }
}
onMounted(() => {
  fetchUserInfo();
  fetchData();
  resetForm(); // 初始化表单数据
  // 示例：观察某个元素
  const element = document.querySelector('.content');
  if (element) {
    resizeObserver.observe(element);
  }
});

onUnmounted(() => {
  // 断开 ResizeObserver 的连接
  resizeObserver.disconnect();
});
</script>

<style scoped>
/* 确保 html 和 body 占满整个视口 */
html, body {
  height: 100%;
  margin: 0;
}

.paginated-list {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 95vh;
  background-color: #f5f7fa;
}

.content {
  width: 100%;
  max-width: 1200px;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.demo-form-inline {
  margin-bottom: 20px;
}

.el-table {
  flex: 1;
  margin-bottom: 20px;
}

.highlight {
  font-weight: bold;
  color: #409EFF;
}

.pagination {
  text-align: right;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
